/**
 * create by young (young2f@outlook.com) on 2020/12/4
 */
'use strict';
const base = require('../base/serviceBase');
const _ = require('lodash');
const moment = require('moment');
const { result } = require('lodash');

module.exports = class extends base {
  async createRecord(body) {
    const { ctx } = this;
    console.log('create record', body);
    const {
      table,
      openingBank,
      account,
      fileList = [],
      accountCode,
      receiptAmount = 0,
      paymentAmount = 0,
      taxRate = '13%'
    } = body;
    if (table === 'Receipt') {
      body.tax = this.getTax(receiptAmount, taxRate);
    }
    if (table === 'Payment') {
      body.tax = this.getTax(paymentAmount, taxRate);
    }
    // 有水单就是结单
    if (fileList.length > 0 && table === 'Receipt') {
      body.tax = this.getTax(receiptAmount, taxRate);
      body.isEnd = '已结单';
    }
    if (fileList.length === 0 && table === 'Receipt') {
      body.isEnd = '未结单';
    }
    const result = await ctx.app.dbs.insert(table, body);

    const res = await ctx.app.dbs.findOne('BankAccount', {
      openingBank,
      account,
      code: accountCode
    },);
    const { balance = 0 } = res;
    /**
     * 付款
     */
    if (table === 'Payment') {
      const amount = balance - paymentAmount;
      const result = await ctx.app.dbs.updateOne('BankAccount', {
        openingBank,
        account,
        code: accountCode
      }, { balance: amount });
    }
    /**
     * 收款
     */
    if (table === 'Receipt') {
      const amount = balance + receiptAmount;
      const result = await ctx.app.dbs.updateOne('BankAccount', {
        openingBank,
        account,
        code: accountCode
      }, { balance: amount });
    }
    return { status: 'ok', result };
  }

  async updateRecord(body) {
    const { ctx } = this;
    const { code, tenantCode, accountName, account, openingBank, treeId, fileList = [], table,taxRate, receiptAmount,paymentAmount} = body;
    console.log('update Record body', body);
    let _accountName = accountName.replace(account, '');
    _accountName = _accountName.replace(openingBank, '');
    _accountName = _accountName.replace(' ', '');

    body._accountName = _accountName;
    if (table === 'Receipt') {
      body.tax = this.getTax(receiptAmount, taxRate);
    }
    if (table === 'Payment') {
      body.tax = this.getTax(paymentAmount, taxRate);
    }
    // 有水单就是结单
    if (fileList.length > 0 && table === 'Receipt') {
      body.isEnd = '已结单';
    }
    if (fileList.length === 0 && table === 'Receipt') {
      body.isEnd = '未结单';
    }
    const result = await ctx.app.dbs.updateOne(table, { code, tenantCode, treeId }, body);
    const { accountCode, oldAmount } = body;
    const res = await ctx.app.dbs.findOne('BankAccount', {
      openingBank,
      account,
      code: accountCode
    },);
    const { balance = 0 } = res;
    /**
     * 付款
     */
    if (table === 'Payment' && oldAmount) {
      const amount = balance + oldAmount - paymentAmount;
      const result = await ctx.app.dbs.updateOne('BankAccount', {
        openingBank,
        account,
        code: accountCode
      }, { balance: amount });
    }

    /**
     * 收款
     */

    if (table === 'Receipt' && oldAmount) {
      const amount = balance - oldAmount + receiptAmount;
      const result = await ctx.app.dbs.updateOne('BankAccount', {
        openingBank,
        account,
        code: accountCode
      }, { balance: amount });
    }
    return { status: 'ok', result };
  }

  async deleteRecord(body) {
    const { ctx } = this;
    let { tenantCode, code, table } = body;

    const result = await ctx.app.dbs.deleteOne(table, { tenantCode, code });
    const { accountCode, paymentAmount, receiptAmount, openingBank, account } = body;
    const res = await ctx.app.dbs.findOne('BankAccount', {
      openingBank,
      account,
      code: accountCode
    },);
    const { balance = 0 } = res;
    /**
     * 付款
     */
    if (table === 'Payment') {
      const amount = balance + paymentAmount;
      const result = await ctx.app.dbs.updateOne('BankAccount', {
        openingBank,
        account,
        code: accountCode
      }, { balance: amount });
    }
    /**
     * 收款
     */
    if (table === 'Receipt') {
      const amount = balance - receiptAmount;
      const result = await ctx.app.dbs.updateOne('BankAccount', {
        openingBank,
        account,
        code: accountCode
      }, { balance: amount });
    }
    return { status: 'ok', result };
  }

  async findRecordStatistics(body) {
    console.log('findRecordStatisticsss', body);
    const res = await this.findRecordMany(body);
    const { result } = res;
    let receipt = 0,
      payment = 0;
    _.map(result, (record) => {
      const { paymentAmount = 0, receiptAmount = 0 } = record;
      receipt += receiptAmount;
      payment += paymentAmount;
    });
    return { status: 'ok', result: { receipt, payment } };
  }

  async taxAssess(body) {
    const { tenantCode, createdTs, accountCode } = body;
    const paymentQuery = { tenantCode };
    if (createdTs && createdTs.length === 2) {
      paymentQuery['createdTs'] = {
        $gte: new Date(moment(createdTs[0])
          .valueOf()),
        $lt: new Date(moment(createdTs[1])
          .valueOf())
      };
    }
    if (accountCode) paymentQuery['accountCode'] = accountCode;
    paymentQuery['taxRate'] = { $ne: '0%' };
    const receiptQuery = _.cloneDeep(paymentQuery);
    paymentQuery['reviewStatus']={ $ne: '驳回' };
    // query['taxRate'] = { $ne: '0%' };
    /**
     * 销售统计
     */
    const paymentList = await this.app.dbs.aggregate('Payment', [
      { $match: { ...paymentQuery } },
    ]);

    const paymentTaxRes = await this.app.dbs.aggregate('Payment', [
      { $match: { ...paymentQuery } },
      { $group: { _id: null, tax: { $sum: '$tax' } } },
    ]);
    /**
     * 采购统计
     */
    const receiptList = await this.app.dbs.aggregate('Receipt', [
      { $match: { ...receiptQuery } },
    ]);

    const receiptTaxRes = await this.app.dbs.aggregate('Receipt', [
      { $match: { ...receiptQuery } },
      { $group: { _id: null, tax: { $sum: '$tax' } } },
    ]);
    const paymentTax = paymentTaxRes.length ? paymentTaxRes[0].tax : 0;
    const receiptTax = receiptTaxRes.length ? receiptTaxRes[0].tax : 0;
    return {
      status: 'ok',
      result: {
        paymentTax,
        receiptTax,
        receiptList,
        paymentList,
      }
    };
  }

  /**
   * 固定资产统计
   * @param body
   * @returns {Promise<{status: string, result: {list: *}}>}
   */
  async fixedAssess(body) {
    const { tenantCode, accountCode, createdTs } = body;
    const query = { tenantCode };
    if (accountCode) query.accountCode = accountCode;
    if (createdTs && createdTs.length === 2) {
      query['createdTs'] = {
        $gte: new Date(moment(createdTs[0])
          .valueOf()),
        $lt: new Date(moment(createdTs[1])
          .valueOf())
      };
    }
    console.log('finance query', query);
//土地、房产、附属工程
// 家具家电
// 办公设备
// 仪器仪表
// 机械设备
// 车辆
    /**
     * 固定资产统计
     */
    query['$or'] = [ { treeName: '土地' }, { treeName: '房产' }, { treeName: '附属工程' },
      { treeName: '家具家电' }, { treeName: '办公设备' }, { treeName: '仪器仪表' }, { treeName: '机械设备' }, { treeName: '车辆' } ];
    const list = await this.app.dbs.find('Payment', query);
    console.log('fixedList', result);

    delete query['$or'];
    query['treeName'] = '土地';
    let landRes = await this.app.dbs.aggregate('Payment', [
      { $match: { ...query } },
      {
        $group: {
          _id: null, // 这里使用null表示对所有文档进行分组，你也可以根据某个字段进行分组
          totalAmount: { $sum: '$paymentAmount' }
        }
      }
    ]);
    const land = landRes.length ? landRes[0].totalAmount : 0;
    query['treeName'] = '房产';
    landRes = await this.app.dbs.aggregate('Payment', [
      { $match: { ...query } },
      {
        $group: {
          _id: null, // 这里使用null表示对所有文档进行分组，你也可以根据某个字段进行分组
          totalAmount: { $sum: '$paymentAmount' }
        }
      }
    ]);
    const estate = landRes.length ? landRes[0].totalAmount : 0;
    query['treeName'] = '附属工程';
    landRes = await this.app.dbs.aggregate('Payment', [
      { $match: { ...query } },
      {
        $group: {
          _id: null, // 这里使用null表示对所有文档进行分组，你也可以根据某个字段进行分组
          totalAmount: { $sum: '$paymentAmount' }
        }
      }
    ]);
    const engineering = landRes.length ? landRes[0].totalAmount : 0;
    query['treeName'] = '家具家电';
    landRes = await this.app.dbs.aggregate('Payment', [
      { $match: { ...query } },
      {
        $group: {
          _id: null, // 这里使用null表示对所有文档进行分组，你也可以根据某个字段进行分组
          totalAmount: { $sum: '$paymentAmount' }
        }
      }
    ]);
    const furniture = landRes.length ? landRes[0].totalAmount : 0;
    query['treeName'] = '办公设备';
    landRes = await this.app.dbs.aggregate('Payment', [
      { $match: { ...query } },
      {
        $group: {
          _id: null, // 这里使用null表示对所有文档进行分组，你也可以根据某个字段进行分组
          totalAmount: { $sum: '$paymentAmount' }
        }
      }
    ]);
    const office = landRes.length ? landRes[0].totalAmount : 0;
    query['treeName'] = '仪器仪表';
    landRes = await this.app.dbs.aggregate('Payment', [
      { $match: { ...query } },
      {
        $group: {
          _id: null, // 这里使用null表示对所有文档进行分组，你也可以根据某个字段进行分组
          totalAmount: { $sum: '$paymentAmount' }
        }
      }
    ]);
    const tool = landRes.length ? landRes[0].totalAmount : 0;
    query['treeName'] = '机械设备';
    landRes = await this.app.dbs.aggregate('Payment', [
      { $match: { ...query } },
      {
        $group: {
          _id: null, // 这里使用null表示对所有文档进行分组，你也可以根据某个字段进行分组
          totalAmount: { $sum: '$paymentAmount' }
        }
      }
    ]);
    const device = landRes.length ? landRes[0].totalAmount : 0;
    query['treeName'] = '车辆';
    landRes = await this.app.dbs.aggregate('Payment', [
      { $match: { ...query } },
      {
        $group: {
          _id: null, // 这里使用null表示对所有文档进行分组，你也可以根据某个字段进行分组
          totalAmount: { $sum: '$paymentAmount' }
        }
      }
    ]);
    const car = landRes.length ? landRes[0].totalAmount : 0;
    return { status: 'ok', result: { land, estate, engineering, furniture, office, tool, device, car, list } };
  }

  async assess(body) {
    const { tenantCode, accountCode, createdTs } = body;
    const query = { tenantCode };
    if (accountCode) query.accountCode = accountCode;
    if (createdTs && createdTs.length === 2) {
      query['createdTs'] = {
        $gte: new Date(moment(createdTs[0])
          .valueOf()),
        $lt: new Date(moment(createdTs[1])
          .valueOf())
      };
    }
    console.log('finance query', query);

    /**
     * 收款统计
     */
    const receiptList = await this.app.dbs.aggregate('Receipt', [
      { $match: { ...query } },
    ]);
    /**
     * 付款
     */
    const paymentList = await this.app.dbs.aggregate('Payment', [
      { $match: { ...query } },
    ]);

    const query1 = { tenantCode };
    if (accountCode) query1.code = accountCode;
    const accountList = await this.app.dbs.find('BankAccount', query1);

    let receipt = 0,
      paymentTotal = 0,
      paymentNoReview = 0,
      paymentReview = 0,
      amountTotal = 0;

    _.map(receiptList, (record) => {
      const { receiptAmount = 0 } = record;
      receipt += receiptAmount;

    });
    _.map(paymentList, (record) => {
      const { paymentAmount = 0, reviewStatus = '待审核' } = record;
      paymentTotal += paymentAmount;
      if (reviewStatus === '同意') {
        paymentReview += paymentAmount;
      } else {
        paymentNoReview += paymentAmount;
      }
    });
    _.map(accountList, (record) => {
      const { balance = 0 } = record;
      amountTotal += balance;
    });

    return {
      status: 'ok',
      result: {
        receipt,
        paymentTotal,
        paymentReview,
        paymentNoReview,
        receiptList,
        paymentList,
        amountTotal,
        accountList
      }
    };
  }

  async findRecord(body) {
    const { ctx } = this;
    const { table } = body;
    delete body['table'];
    console.log('finance query', body);
    const result = await ctx.app.dbs.findOne(table, body);
    console.log('finance query result', result);
    return { status: 'ok', result };
  }

  async findRecordMany(body) {
    const { ctx, service } = this;
    const { table, tenantCode, treeId, createdTs } = body;
    delete body['table'];
    const { key } = body;
    const _key = key ? key : 'createdTs';

    const sort = {};
    sort[_key] = -1;
    const schema = await service.globalService.getModel({ table });
    const query = treeId ? { tenantCode, treeId } : { tenantCode };
    _.map(body, (value, key) => {
      const temp = _.find(schema, (it, k) => {
        return k === key && key !== 'treeId';
      });

      if (temp) {
        const { _type } = temp;
        query[key] = this.getValue(_type, value, key);
      }
    });
    if (createdTs && createdTs.length === 2) {
      query['createdTs'] = {
        $gte: new Date(moment(createdTs[0])
          .valueOf()),
        $lt: new Date(moment(createdTs[1])
          .valueOf())
      };
    }
    const result = await ctx.app.dbs.aggregate(table, [
      { $match: { ...query } },
      { $sort: { ...sort } },
    ]);
    //  console.log('rr',result);
    return { status: 'ok', result };
  }

  /**
   * 查找主材和辅材的采购付款
   * @param body
   * @returns {Promise<{status: string, result: *}>}
   */
  async findProcureRecordMany(body) {
    const { ctx, service } = this;
    const { table, tenantCode, treeId, createdTs, treeName, vendorName } = body;
    delete body['table'];
    const { key } = body;
    const _key = key ? key : 'createdTs';

    const sort = {};
    sort[_key] = -1;

    const query = { tenantCode };
    query['$or'] = [ { treeMark: 'TRE-PROCURE-MAIN' }, { treeMark: 'TRE-PROCURE-AUX' } ];
    // query['treeName'] = { $or: [ '主材', '辅材' ] };
    treeName ? query['treeName'] = { $regex: treeName } : undefined;
    vendorName ? query['vendorName'] = { $regex: vendorName } : undefined;
    if (createdTs && createdTs.length === 2) {
      query['createdTs'] = {
        $gte: new Date(moment(createdTs[0])
          .valueOf()),
        $lt: new Date(moment(createdTs[1])
          .valueOf())
      };
    }
    console.log('findProcureRecordMany query', query);
    const result = await ctx.app.dbs.find(table, query);
    console.log('findProcureRecordMany rr', result);

    return { status: 'ok', result };
  }

  async procureRecordAssess(body) {
    const { ctx, service } = this;
    const { table, tenantCode, treeId, createdTs, treeName, vendorName } = body;
    delete body['table'];
    const { key } = body;
    const _key = key ? key : 'createdTs';

    const sort = {};
    sort[_key] = -1;

    const query = { tenantCode };
    query['$or'] = [ { treeMark: 'TRE-PROCURE-MAIN' }, { treeMark: 'TRE-PROCURE-AUX' } ];
    // query['treeName'] = { $or: [ '主材', '辅材' ] };
    treeName ? query['treeName'] = { $regex: treeName } : undefined;
    vendorName ? query['vendorName'] = { $regex: vendorName } : undefined;
    if (createdTs && createdTs.length === 2) {
      query['createdTs'] = {
        $gte: new Date(moment(createdTs[0])
          .valueOf()),
        $lt: new Date(moment(createdTs[1])
          .valueOf())
      };
    }
    console.log('findProcureRecordMany query', query);
    const result = await ctx.app.dbs.aggregate('Payment', [
      { $match: { ...query } },
      {
        $group: {
          _id: null, // 或者使用具体的字段进行分组，这里使用null表示不需要分组
          payment: { $sum: '$paymentAmount' } // 对value字段的值进行累加
        }
      }
    ]);
    const payment = result.length ? result[0].payment : 0;
    console.log('findProcureRecordMany assess rr', result);
    return { status: 'ok', result: { payment } };
  }

  async exportRecordExcel(body) {
    const { ctx, service } = this;
    console.log('find customer many', body);
    const { table, tenantCode } = body;
    delete body['table'];
    const query = { tenantCode };
    const { receipt = [], payment = [] } = body;
    delete body['tenantName'];
    delete body['tenantCode'];
    delete body['receipt'];
    delete body['payment'];
    const schema = await service.globalService.getModel({ table: 'Receipt' });
    _.map(body, (value, key) => {
      const temp = _.find(schema, (it, k) => {
        return k === key;
      });

      if (temp) {
        const { _type } = temp;
        query[key] = this.getValue(_type, value, key);
      }
    });

    _.map(receipt, (value, key) => {
      const temp = _.find(schema.receipt.cols, it => {
        return it.key === key;
      });

      if (temp) {
        const { _type } = temp;
        const _key = `receipt.${key}`;
        query[_key] = this.getValue(_type, value, _key);
      }
    });

    _.map(payment, (value, key) => {
      const temp = _.find(schema.payment.cols, it => {
        return it.key === key;
      });

      if (temp) {
        const { _type } = temp;
        const _key = `payment.${key}`;
        query[_key] = this.getValue(_type, value, _key);
      }
    });
    const { key } = body;
    const _key = key ? key : 'createdTs';

    const sort = {};
    sort[_key] = -1;

    const data = await ctx.app.dbs.aggregate(table, [
      { $match: { ...query } },
      { $sort: { ...sort } },
    ]);
    const mod = ctx.model['Receipt'];
    const _header = mod.schema.obj;
    const header = [];
    _.map(_header, (item, key) => {
      item.dataIndex = key;
      item.key = key;
      header.push(item);
    });
    return { status: 'ok', result: { header, data } };
  }


  async deleteInvoiceRecord(body) {
    const { ctx } = this;
    let { tenantCode, recordId } = body;
    const result = await ctx.app.dbs.deleteOne('Invoice', { tenantCode, recordId });
    return { status: 'ok', result };
  }

  async updateInvoiceRecord(body) {
    const { ctx } = this;
    let { tenantCode, recordId } = body;
    const result = await ctx.app.dbs.updateOne('Invoice', { tenantCode, recordId }, body);
    return { status: 'ok', result };
  }

  async findInvoiceRecordMany(body) {
    const { ctx, service } = this;
    const { type, tenantCode, createdTs, division, name } = body;

    const { key } = body;
    const _key = key ? key : 'createdTs';

    const sort = {};
    sort[_key] = -1;
    const query = { type, tenantCode };
    if (createdTs && createdTs.length === 2) {
      query['createdTs'] = {
        $gte: new Date(moment(createdTs[0])
          .valueOf()),
        $lt: new Date(moment(createdTs[1])
          .valueOf())
      };
    }
    if (name) {
      query['name'] = { $regex: name };
    }
    if (division) {
      query['division'] = { $regex: division };
    }

    const result = await ctx.app.dbs.aggregate('Invoice', [
      { $match: { ...query } },
      { $sort: { ...sort } },
    ]);
    //  console.log('rr',result);
    return { status: 'ok', result };
  }

  /**
   * 查询开票订单
   * @param body
   * @returns {Promise<{status: string, result: *}>}
   */
  async findInvoiceSalesMany(body) {
    const { ctx, service } = this;
    const { type, tenantCode, createdTs, division, name } = body;

    const { key } = body;
    const _key = key ? key : 'createdTs';

    const sort = {};
    sort[_key] = -1;
    const query = { tenantCode };
    if (createdTs && createdTs.length === 2) {
      query['createdTs'] = {
        $gte: new Date(moment(createdTs[0])
          .valueOf()),
        $lt: new Date(moment(createdTs[1])
          .valueOf())
      };
    }
    if (name) {
      query['customer'] = { $regex: name };
    }
    if (division) {
      query['division'] = { $regex: division };
    }
    query['taxRate'] = { $ne: '0%' };

    const result = await ctx.app.dbs.aggregate('SalesOrder', [
      { $match: { ...query } },
      { $sort: { ...sort } },
    ]);
    //  console.log('rr',result);
    return { status: 'ok', result };
  }

  /**
   * 开票统计
   * @param body
   * @returns {Promise<{status: string, result: *}>}
   */
  async invoiceAssess(body) {
    const { ctx, service } = this;
    const { type, tenantCode, createdTs, division, name } = body;

    const { key } = body;
    const _key = key ? key : 'createdTs';

    const sort = {};
    sort[_key] = -1;
    const query = { type, tenantCode };
    if (createdTs && createdTs.length === 2) {
      query['createdTs'] = {
        $gte: new Date(moment(createdTs[0])
          .valueOf()),
        $lt: new Date(moment(createdTs[1])
          .valueOf())
      };
    }
    if (name) {
      query['customer'] = { $regex: name };
    }
    if (division) {
      query['division'] = { $regex: division };
    }

    /**
     * 统计已开票
     */

    console.log('invoiceAssess query', query);
    const invoiceAssess = { invoicingTotal: 10, salesInvoiceTotal: 10 };
    const result1 = await ctx.app.dbs.aggregate('Invoice', [
      { $match: { ...query } },
      { $group: { _id: null, invoicingTotal: { $sum: '$amount' } } },
    ]);
    console.log('invoiceAssess res', result1);
    if (result1.length > 0) {
      invoiceAssess.invoicingTotal = result1[0].invoicingTotal;
    }
    query['taxRate'] = { $ne: '0%' };
    delete query['type'];
    const result = await ctx.app.dbs.aggregate('SalesOrder', [
      { $match: { ...query } },
      { $group: { _id: null, salesInvoiceTotal: { $sum: '$amount' } } },
    ]);
    if (result.length > 0) {
      invoiceAssess.salesInvoiceTotal = result[0].salesInvoiceTotal;
    }
    //  console.log('rr',result);
    return { status: 'ok', result: invoiceAssess };
  }

  /**
   * 查询收票采购单
   * @param body
   * @returns {Promise<{status: string, result: *}>}
   */
  async findInvoiceProcureMany(body) {
    const { ctx, service } = this;
    const { type, tenantCode, createdTs, division, name } = body;

    const { key } = body;
    const _key = key ? key : 'createdTs';

    const sort = {};
    sort[_key] = -1;
    const query = { tenantCode };
    if (createdTs && createdTs.length === 2) {
      query['createdTs'] = {
        $gte: new Date(moment(createdTs[0])
          .valueOf()),
        $lt: new Date(moment(createdTs[1])
          .valueOf())
      };
    }
    if (name) {
      query['customer'] = { $regex: name };
    }
    if (division) {
      query['division'] = { $regex: division };
    }
    query['taxRate'] = { $ne: '0%' };

    const result = await ctx.app.dbs.aggregate('ProcureOrder', [
      { $match: { ...query } },
      { $sort: { ...sort } },
    ]);
    //  console.log('rr',result);
    return { status: 'ok', result };
  }

  /**
   * 收票统计
   * @param body
   * @returns {Promise<{status: string, result: *}>}
   */
  async invoiceReceiptAssess(body) {
    const { ctx, service } = this;
    const { type, tenantCode, createdTs, division, name } = body;

    const { key } = body;
    const _key = key ? key : 'createdTs';

    const sort = {};
    sort[_key] = -1;
    const query = { type, tenantCode };
    if (createdTs && createdTs.length === 2) {
      query['createdTs'] = {
        $gte: new Date(moment(createdTs[0])
          .valueOf()),
        $lt: new Date(moment(createdTs[1])
          .valueOf())
      };
    }
    if (name) {
      query['customer'] = { $regex: name };
    }
    if (division) {
      query['division'] = { $regex: division };
    }

    /**
     * 统计已开票
     */

    console.log('invoiceAssess query', query);
    const invoiceAssess = { invoicingTotal: 10, salesInvoiceTotal: 10 };
    const result1 = await ctx.app.dbs.aggregate('Invoice', [
      { $match: { ...query } },
      { $group: { _id: null, invoiceReceiptTotal: { $sum: '$amount' } } },
    ]);
    console.log('invoiceAssess res', result1);
    if (result1.length > 0) {
      invoiceAssess.invoiceReceiptTotal = result1[0].invoiceReceiptTotal;
    }
    query['taxRate'] = { $ne: '0%' };
    delete query['type'];
    const result = await ctx.app.dbs.aggregate('ProcureOrder', [
      { $match: { ...query } },
      { $group: { _id: null, procureInvoiceTotal: { $sum: '$amount' } } },
    ]);
    if (result.length > 0) {
      invoiceAssess.procureInvoiceTotal = result[0].procureInvoiceTotal;
    }
    //  console.log('rr',result);
    return { status: 'ok', result: invoiceAssess };
  }

  async findPaymentMany(body) {
    const { ctx } = this;
    const { tenantCode, createdTs, path } = body;
    if (createdTs && createdTs.length > 0) {
      body['createdTs'] = {
        $gte: new Date(moment(createdTs[0])
          .valueOf()),
        $lt: new Date(moment(createdTs[1])
          .valueOf())
      };
    }

    const group = {
      $group: {
        _id: null, // 这里使用null表示不需要基于某个字段进行分组，直接计算总和
        amount: { $sum: `$${path}` } // 计算amount字段的总和
      }
    };
    delete body['path'];
    console.log('find payment body', body, group);
    const res = await ctx.app.dbs.aggregate('SalesOrder', [
      { $match: body },
      group
    ]);
    console.log('find payment', res);
    const amount = res.length ? res[0].amount : 0;
    const data = await ctx.app.dbs.find('SalesOrder', body);
    return { status: 'ok', result: { amount, data } };
  }

  async findShippingFeeMany(body) {
    const { ctx } = this;

    return { status: 'ok', result };
  }

  async findPublicFeeMany(body) {
    const { ctx } = this;

    return { status: 'ok', result };
  }

  async findLobarFeeMany(body) {
    const { ctx } = this;

    return { status: 'ok', result };
  }
};
